<!-- 多购领料作业：蹇泽阳 -->
<template>
  <div class="app-container">
    <div class="flex">
      <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
      <Find :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" />
    </div>
    <div class="flex">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" style="width: 100%">
        <h1 class="f16">多购领料作业</h1>
        <Table
          @selectList="selectTableList"
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
        />
        <el-card shadow="never" :body-style="{ padding: '5px' }">
          <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
        </el-card>
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" style="width: 100%">
        <h1 class="f16">已领料明细档</h1>
        <Table @selectList="selectTableList2" :tableHeader="tableHeader2" :tableData="tableData2" selection class="mt10" :isLoading="isLoading2" />
        <PageModule :PageData="{ total: total2, buttonS: true }" @pageSizeChange="handleSizeChange2" @pageChange="handleCurrentChange2" />
      </el-card>
    </div>

    <div class="qrCodeContainer" style="width: 450px; height: 50px; display: none; width: 100%">
      <h1 class="title" style="width: 480px; margin-left: 27%">{{ $t(`Print.RongyangGarmentCoLtdInstructionPickingList`) }}</h1>
      <div style="width: 95%; margin: auto" v-for="(item, index) in printList" :key="index">
        <div style="display: flex; width: 100%; font-size: 13px; justify-content: space-between">
          <h2 style="margin-left: 70px; font-size: 13px">{{ $t(`Print.ThePickingOrderNumber`) }}:{{ index }}</h2>
          <h2 style="margin-left: 70px; font-size: 13px">{{ $t(`Print.RequisitionDate`) }}:{{ userInfo?.lastLogin.split(' ')[0] }}</h2>
          <h2 style="margin-left: 70px; font-size: 13px">{{ $t(`Print.Department`) }}:{{ userInfo?.deptName }}</h2>
          <h2 style="margin-left: 70px; font-size: 13px">{{ $t(`Print.DateOfPrinting`) }}:{{ formatCurrentDateTime(currentDate) }}</h2>
        </div>

        <div style="width: 100%">
          <table style="width: 100%; font-size: 13px">
            <thead>
              <tr>
                <th>{{ $t(`Print.Directives`) }}</th>
                <th>{{ $t(`Print.Body`) }}</th>
                <th>{{ $t(`Print.OrderVolume`) }}</th>
                <th>{{ $t(`Print.MaterialColorKey`) }}</th>
                <th>{{ $t(`Print.MaterialName`) }}</th>
                <th>{{ $t(`Print.Specification`) }}</th>
                <th>{{ $t(`Print.Unit`) }}</th>
                <th>{{ $t(`Print.Consumption`) }}</th>
                <th>{{ $t(`Print.PleasePickUpTheAmount`) }}</th>
                <th>{{ $t(`Print.Remark`) }}</th>
                <!-- 更多的表头单元格 -->
              </tr>
            </thead>
            <tbody>
              <tr v-for="(iten1, index) in item" :key="index">
                <td>{{ iten1.lotNo }}</td>
                <td>{{ iten1.style }}</td>
                <td>{{ iten1.orderQty }}</td>
                <td>{{ iten1.mtlColor }}</td>
                <td>{{ iten1.mtlName }}</td>
                <td>{{ iten1.mtlUnit }}</td>
                <td>{{ iten1.mtlSpec }}</td>
                <td>{{ iten1.ttlUsage }}</td>
                <td>{{ iten1.reqQty }}</td>
                <td>{{ iten1.remark }}</td>
                <!-- 更多的数据单元格 -->
              </tr>
              <!-- 更多的行 -->
            </tbody>
            <!-- 可选的 tfoot 部分 -->
          </table>
          <div style="display: flex; justify-content: space-between; width: 85%; font-size: 17px; width: 80%; margin: auto">
            <h2 style="font-size: 13px">{{ $t(`Print.HeadOfDepartment`) }}:</h2>
            <h2 style="font-size: 13px">{{ $t(`Print.WarehouseKeeper`) }}:</h2>
            <h2 style="font-size: 13px">{{ $t(`Print.Picker`) }}:{{ userInfo.chiName }}</h2>
          </div>

          <!-- <Table :tableHeader="tableHeader5" :tableData="slipNoList" /> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="MultiplePurchasingAndPickingOperations">
import { Jzhcn } from '@/i18n'
import JMessage from '@/utils/JMessage'
import LoginWork from '@/utils/LoginWork'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { watch } from 'vue'
import { onMounted } from 'vue'
import { ref } from 'vue'

const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入领料单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未领',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已领',
    checked: false
  },
  {
    type: 'button',
    checkboxLabel: '领料批处理',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
])
const formList2 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入领料单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '打印领料单',
    bgColor: '#1890FF'
  }
])

// 表一模块
const selectedLists = ref([]) as any
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '领料批处理') {
    const resList = selectedLists.value.map(async (item: any) => {
      return new Promise(async (resolve, reject) => {
        const res = (await LoginWork.post('/produce/moreCheck', {
          reqQty: item.notActQty,
          ...item
        })) as any
        return resolve(res)
      })
    })
    const res2 = await Promise.all(resList)

    console.log(res2)

    const res = (await LoginWork.post(
      '/produce/moreCollar',
      selectedLists.value.map((item: any) => {
        item.reqQty = item.notActQty
        return item
      })
    )) as any
    if (res.code === 200) {
      JMessage.success('领料批处理成功')
      getTableList()
      getTableList2()
    } else {
      JMessage.error(res.message)
    }
  }
}
const findClicked2 = async (content: string) => {
  if (content === '置空') {
    formList2.value.forEach((item: any) => {
      item.inputValue = ''
    })
  }
  if (content === '打印领料单') {
    const res = (await LoginWork.put('/produce/PrintMaterialRequisitionForm', selectedLists2.value)) as any
    if (res.code === 200) {
      await printQRCode()
      JMessage.success('打印成功')
      getTableList()
      getTableList2()
    } else {
      JMessage.error(res.message)
    }
  }
}
const tableData = ref([])
const isLoading = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 表格计算函数
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '未领')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '已领')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return ''
  } else if (Unaudited.checked) {
    return '0'
  } else if (Audited.checked) {
    return '1'
  } else {
    JMessage.warning('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return ''
  }
}
const tableHeader = ref([
  {
    width: '100',
    label: '指令',
    prop: 'lotNo',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    width: '100',
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    width: '100',
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    width: '100',
    label: '已领量',
    prop: 'ttlUsage',
    change: true
  },
  {
    width: '100',
    label: '未领量',
    prop: 'notActQty',
    change: true
  }
])
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  console.log(formList.value)

  let tableDataList = await service.post<any, any>('/produce/moreList', {
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令'
    )?.inputValue,
    mtlName: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入材料名称'
    )?.inputValue,
    slipNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入领料单号'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    status: cfmFlag() //	有无欠数(Y/N)	string	body	true
  })
  isLoading.value = false
  tableData.value = tableDataList.list
  total.value = tableDataList.total
  currentRow()
  // summaryData.value[0].num = tableDataList.sum[0].orderCount
  // summaryData.value[1].num = tableDataList.sum[0].surplusCount
}, 500)
const userInfo = ref({}) as any
onMounted(() => {
  userInfo.value = JSON.parse(sessionStorage.getItem('userInfo') as any)
  getTableList()
  getTableList2()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0]) => {
  currentTableRow.value = row
}

const tableData2 = ref([])
const isLoading2 = ref(false)
// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const tableHeader2 = ref([
  {
    width: '100',
    label: '领料单号',
    prop: 'slipNo',
    change: true
  },
  {
    width: '100',
    label: '指令',
    prop: 'lotNo',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    width: '100',
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    width: '100',
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    label: '已请领量',
    prop: 'reqQty',
    change: true
  }
])
const selectedLists2 = ref([]) as any
const printList = ref([]) as any
const selectTableList2 = (selectedList: any) => {
  selectedLists2.value = selectedList

  printList.value = selectedList.reduce((acc: any, item: any) => {
    if (!acc[item.slipNo]) {
      acc[item.slipNo] = []
    }
    acc[item.slipNo].push(item)
    return acc
  }, {})
}
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList = await service.post<any, any>('/produce/moreList2', {
    lotNo: formList2.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令'
    )?.inputValue,
    mtlName: formList2.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入材料名称'
    )?.inputValue,
    slipNo: formList2.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入领料单号'
    )?.inputValue,
    pageNum: currentPage2.value,
    pageSize: pageSize2.value
  })
  isLoading2.value = false
  tableData2.value = tableDataList.list
  total2.value = tableDataList.total
  currentRow()
  // summaryData.value[0].num = tableDataList.sum[0].orderCount
  // summaryData.value[1].num = tableDataList.sum[0].surplusCount
}, 500)
watch(
  () =>
    formList2.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList2()
  }
)
const printQRCode = () => {
  const qrCodeContainer = document.querySelector<any>('.qrCodeContainer')
  if (qrCodeContainer) {
    // 临时显示 .qrCodeContainer 以获取其内容
    qrCodeContainer.style.display = 'block'

    const printWindow = window.open('', '_blank')
    printWindow!.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>打印指令领料作业</title>
          <link rel="stylesheet" type="text/css" href="print.css" media="print">
          <style>
            body, html {
              margin: 0;
              padding: 0;
            }
            @page {
              size: auto;
              margin: 3mm;
            }
            @media print {
                /* 打印时的样式 */


                /* 其他打印样式 */
            }
            h2 {
                    margin-left: initial; /* 或者设置适合打印的左边距 */
                    page-break-inside: avoid; /* 避免在h2元素内部分页 */
                }


            table, th, td {
                    border: 1px solid black;
                    border-collapse: collapse;
                    text-align: center;
                  }
                  th, td {
                    padding: 5px; /* 设置内边距 */
                    text-align: left; /* 设置文本对齐方式 */
                    text-align: center;
                    font-size:11px
                  }
                  .double-line {
                    border-top: 2px dashed red;
                    border-bottom: 2px dashed red;
                    text-align: center;
                  }

            /* 可以在这里添加更多自定义的打印样式 */
          </style>
        </head>
        <body>
    `)

    // 将 .qrCodeContainer 的内容复制到打印窗口的 body 中
    const cloneContainer = qrCodeContainer.cloneNode(true)
    printWindow!.document.body.appendChild(cloneContainer)

    printWindow!.document.write(`
        </body>
      </html>
    `)
    printWindow!.document.close()

    // 开始打印
    printWindow!.print()

    // 打印完成后，可以恢复 .qrCodeContainer 的原始显示状态
    qrCodeContainer.style.display = 'none'
  }
  return Promise.resolve()
}
// 日期
const currentDate = ref(new Date())
const formatCurrentDateTime = (date?: Date) => {
  const year = date!.getFullYear()
  const month = String(date!.getMonth() + 1).padStart(2, '0') // 使用padStart确保月份是两位数
  const day = String(date!.getDate()).padStart(2, '0') // 使用padStart确保日期是两位数
  const hours = String(date!.getHours()).padStart(2, '0') // 小时
  const minutes = String(date!.getMinutes()).padStart(2, '0') // 分钟
  const seconds = String(date!.getSeconds()).padStart(2, '0') // 秒

  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>
